package cn.my.android_demo.api;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiUtil {
    public static Retrofit retrofitClient(String token, String apiUrl) {
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS).
                addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        Request request = original.newBuilder()
//                                .addHeader(AUTH_HEADER_KEY
//                                        , BEARER_HEADER_VALUE
//                                                + getToken())
                                .method(original.method(), original.body())
                                .build();
                        return chain.proceed(request);
                    }
                }).build();
        return new Retrofit.Builder()
                .baseUrl(apiUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    public synchronized String getToken1(){
        final String token = "";
        //对 token 进行有效判断，有效则使用原有的；无效则对 token 进行刷新操作
        // ⚠️刷新 token 的接口要使用同步操作，否则无用
        //....
        return token;
    }
    private Lock mLock = new ReentrantLock();
    public String getToken2(){
        mLock.lock();
        try{
            //需要上锁的代码块
        }finally{
            mLock.unlock();
        }
        return "";
    }
    public synchronized String getToken(){
        final String token = "";
//        TokenEntity entity = UserUtil.getInstance().getToken();//获取登录时返回的 token 实体
//        long startTime = getStartTime();//获取 token 时的时间，单位：s
//        long currentTime = System.currentTimeMillis()/1000;//获取当前时间
//        //判断 token 的有效期是否在时间段内
//        if ((currentTime - startTime) < Long.parseLong(entity.getExpiresIn())) {
//            token = entity.getToken();
//        } else {
//            //根据 refreshToken 刷新 token，获得最新 token
//            //⚠️需要使用同步请求
//        }
        return token;
    }

    /**
     * 通过okhttpClient来设置证书
     * @param clientBuilder OKhttpClient.builder
     * @param certificates 读取证书的InputStream
     */
//    public void setCertificates(OkHttpClient.Builder clientBuilder, InputStream... certificates) {
//        try {
//            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keyStore.load(null);
//            int index = 0;
//            for (InputStream certificate : certificates) {
//                String certificateAlias = Integer.toString(index++);
//                keyStore.setCertificateEntry(certificateAlias, certificateFactory
//                        .generateCertificate(certificate));
//                try {
//                    if (certificate != null)
//                        certificate.close();
//                } catch (IOException e) {
//                }
//            }
//            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
//                    TrustManagerFactory.getDefaultAlgorithm());
//            trustManagerFactory.init(keyStore);
//            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
//            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
//                throw new IllegalStateException("Unexpected default trust managers:"
//                        + Arrays.toString(trustManagers));
//            }
//            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
//            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
//            clientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}
